package datastructure.map;

public class LinkedListMap<K, V> implements Map<K, V> {

    // 定义节点
    private class Node {
        K key;
        V value;
        Node next;

        // 定义构造
        public Node() {
            this(null, null, null);

        }

        public Node(K key, V value) {
            this(key, value, null);
        }

        public Node(K key, V value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }

    private Node dummyHead;
    private int size;

    public LinkedListMap() {
        dummyHead = new Node();
        size = 0;
    }

    // 获取指定节点根据
    public Node getNode(K key) {
        Node cur = dummyHead.next;
        while (cur != null) {
            if (cur.key.equals(key)) {
                return cur;
            }
            cur = cur.next;
        }
        // 循环遍历完成后如果还没有找到就返回null
        return null;
    }

    @Override
    public void add(K key, V value) {
        Node node = getNode(key);
        if (node != null) {
            node.value = value;
        } else {
            dummyHead.next = new Node(key, value, dummyHead.next);
            size++;
        }

    }

    @Override
    public V remove(K key) {
        Node prev = dummyHead;
        while (prev.next != null) {
            if (prev.next.key.equals(key)) {
                // 找到key
                break;
            }
            // 未找到
            prev = prev.next;

        }

        if (prev.next != null) {
            // 要删除的元素为
            Node delNode = prev.next;
            prev.next = delNode.next;
            delNode.next = null;
            size--;
            return delNode.value;
        }
        return null;
    }

    @Override
    public boolean contains(K key) {
        if (getNode(key) != null) {
            return true;
        }
        return false;
    }

    @Override
    public V get(K key) {
        Node node = getNode(key);
        return node.value;
    }

    @Override
    public void set(K key, V newValue) {
        Node node = getNode(key);
        if (node != null) {
            node.value = newValue;
        } else {
            throw new IllegalAccessError("没有找到该key值");
        }
    }

    @Override
    public int getSize() {

        return size;
    }

    @Override
    public boolean isEmpty() {

        return size == 0;
    }

}
